package org.thomias.exo1.tcp.agent;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {
	public void start() {
		try {
			ServerSocket server = null;
			Socket client = null;
			try {
				server = new ServerSocket(22222);
				println("Ecoute du port 22222...");
				while (true) {
					client = server.accept();
					if (handleRequest(client) == false) {
						break;
					}
					if (client != null) {
						client.close();
					}
				}

			} finally {
				if (server != null) {
					server.close();
				}
				if (client != null) {
					client.close();
				}
			}
		} catch (Exception e) {

		}
	}

	public static void println(String msg) {
		System.out.println(msg);
	}

	private boolean handleRequest(Socket client) {
		boolean result = true;
		try {
			PrintStream out = null;
			BufferedReader in = null;
			try {
				out = new PrintStream(client.getOutputStream());
				in = new BufferedReader(new InputStreamReader(
						client.getInputStream()));
				String request = in.readLine();
				if (request.equals("/quit")) {
					result = false;
				} else {
					println("(Server)Received from Client: " + request);
					out.println(request);
				}
			} finally {
				in.close();
				out.close();
			}
		} catch (Exception e) {
		}
		return result;
	}

	public void dialog() {

	}
}
